
from dvadmin.lowcode.models import Schema
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from rest_framework.decorators import action
from django.core.cache import cache

from dvadmin.utils.json_response import SuccessResponse, ErrorResponse, DetailResponse
from dvadmin.system.models import Menu
import json
class SchemaSerializer(CustomModelSerializer):
    """
    """
    class Meta:
        model = Schema
        fields = "__all__"
        read_only_fields = ["id"]





class SchemaViewSet(CustomModelViewSet):
    """
    页面模型管理
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    authentication_classes = []
    permission_classes = []
    queryset = Schema.objects.all()
    serializer_class = SchemaSerializer
    extra_filter_backends = []
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        # print('instance',instance.is_login)
        # print('===',self.request.user)
        # user = request.user
        serializer = self.get_serializer(instance)
        return DetailResponse(data=serializer.data, msg="获取成功")

class SchemaPerViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = Schema.objects.all()
    serializer_class = SchemaSerializer
    extra_filter_backends = []

    @action(methods=['GET'], detail=True)
    def getMenuSchema(self, request,*args, **kwargs):
        """
        /id/ 根据ID获取菜单的模板数据
        """
        instance = self.get_object()
        # print(instance.schema,instance.id,instance.name)
        # data = {}
        # if not instance.schema:
        #     """如果不存在则添加数据"""
        #     obj = Schema.objects.get(name='home')
        #     objdata = Schema.objects.create(name=instance.name,schema=obj.schema,menu_id=instance.id)
        #     instance.schema = objdata
        #     instance.save()
        #     data = {'schema_id':obj.id,'schema':json.loads(obj.schema)}
        # else:
        #     data = {'schema_id':instance.schema.id,'schema':json.loads(instance.schema.schema)}
        # serializer = self.get_serializer(instance)
        """用于获取schema模板数据，如果没有则直接创建一个在返回"""

        return DetailResponse(data=[], msg="获取成功")
    @action(methods=['GET'], detail=True, permission_classes=[])
    def renderschema(self, request,*args, **kwargs):
        """
        根据页面ID获取相关数据
        """
        instance = self.get_object()
        query = self.queryset.filter(menu_id= instance.menu_id).order_by("-create_datetime").first()
        serializer = self.get_serializer(query)
        return DetailResponse(data=serializer.data, msg="获取成功")
    @action(methods=['GET'], detail=False, permission_classes=[])
    def releaseschema(self, request,*args, **kwargs):
        """
        根据页面ID获取相关数据  返回生产数据 release
        """
        menuid = request.query_params['menuid']
        queryobj = Menu.objects.get(id =menuid)
        data = {'schema_id': queryobj.schema_id, 'schema': queryobj.schema.schema}
        return DetailResponse(data=data, msg="获取成功")

    @action(methods=['POST'], detail=False)
    def releasesave(self, request,*args, **kwargs):
        """
        获取菜单ID,和schemaid，把 schemaid存储到在用的schema里面。
        """
        query_params = request.data
        menuid = query_params.get("menuid",None)
        schemaid = query_params.get("schemaid",None)
        if not menuid  and not schemaid:
            return ErrorResponse(data=[], msg="参数存在问题")

        try:
            menuobj = Menu.objects.get(id = menuid)
            menuobj.schema_id = schemaid
            menuobj.save()
            cacheName = "{}_{}".format('schema',menuobj.web_path[1:] )
            cache.delete(cacheName)
        except Exception as e:
            return ErrorResponse(data=[], msg=e)
        return DetailResponse(data=[], msg="获取成功")